#define _CRT_SECURE_NO_WARNINGS 1
#include "SeqList.h"

void SLTInit(SLT* ps)
{
	assert(ps);
	ps->data = (SLTDataType*)malloc(sizeof(SLTDataType)* 4);
	if (ps->data == NULL)
	{
		perror("malloc fail");
		return;
	}

	ps->capacity = 4;
	ps->size = 0;
}

void SLTDestroy(SLT* ps)
{
	assert(ps);
	free(ps->data);
	ps->size = ps->capacity = 0;
}

void SLTCheckCapacity(SLT* ps)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		SLTDataType* tmp = (SLTDataType*)realloc(ps->data, sizeof(SLTDataType) * (ps->capacity * 2));
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}

		ps->data = tmp;
		tmp = NULL;
		ps->capacity *= 2;
	}

}

void SLTPrint(SLT* ps)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->data[i]);
	}
	printf("\n");
}

void SLTPushBack(SLT* ps, SLTDataType x)
{
	//assert(ps);
	//SLTCheckCapacity(ps);
	//ps->data[ps->size] = x;
	//ps->size++;
	SLTInsert(ps, ps->size, x);
}


void SLTPopBack(SLT* ps)
{
	//assert(ps);
	//assert(ps->size > 0);
	//ps->size--;
	SLTErase(ps, ps->size - 1);
}


void SLTPushFront(SLT* ps, SLTDataType x)
{
	assert(ps);

	if (ps->size == 0)
	{
		ps->data[ps->size] = x;
		ps->size++;
	}
	else
	{
		int end = ps->size-1;
		SLTCheckCapacity(ps);
		while (end >= 0)
		{
			ps->data[end + 1] = ps->data[end];
			end--;
		}

		ps->data[0] = x;
		ps->size++;
	}
	// SLTInsert(ps, 0, x);
}

void SLTPopFront(SLT* ps)
{
	assert(ps);
	assert(ps->size > 0);
	int begin = 0;
	while (begin < ps->size)
	{
		ps->data[begin] = ps->data[begin + 1];
		begin++;
	}
	ps->size--;
	//SLTErase(ps, 0);
}


int SLTFindNode(SLT* ps, SLTDataType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->data[i] == x)
			return i;
	}

	return -1;
}

void SLTInsert(SLT* ps, int pos, SLTDataType x)
{
	assert(ps);
	SLTCheckCapacity(ps);
	int end = ps->size;
	while (end > pos)
	{
		ps->data[end] = ps->data[end - 1];
		end--;
	}
	ps->data[pos] = x;
	ps->size++;

}

void SLTErase(SLT* ps, int pos)
{
	assert(ps);
	assert(ps->size > 0);
	int posNext = pos + 1;
	while (posNext < ps->size)
	{
		ps->data[posNext - 1] = ps->data[posNext];
		posNext++;
	}

	ps->size--;
}